<?
//Classe data-base
class rglDb {
   public $oDB = null;
   public $aObjRes = array();
   public $aError = array();
   public $aErrno = array();
   public $aSql = array();
   public $aLastInsertId = array();
   
   //costruttore - per ora considera solo le credenziali MySQL di pers/inc.config.php
   function rglDb() {
      global $objSess;
      $this->oDB = @new mysqli(RGL_DB_HOST, RGL_DB_USER, RGL_DB_PWD, RGL_DB_NAME);
      if ($this->oDB->connect_errno > 0) {
         rglErr('('.RGL_DB_HOST.'/'.RGL_DB_USER.') DB connect error : '
         	.$this->oDB->connect_errno." - ".$this->oDB->connect_error);
      }      
   }
   
   function query($sql,$name='default',$stopOnError=true) {
   	return $this->exec($sql,$name,$stopOnError);
   }
   
   function exec($sql,$name='default',$stopOnError=true) {
      $this->aSql[$name] = $sql;
      $this->aObjRes[$name] = $this->oDB->query($sql);
      if ($stopOnError and $this->oDB->errno > 0) {
         rglErr('Errore DB : '.$this->oDB->errno." = ".$this->oDB->error."\r\n".$sql);
      }
      $this->aErrno[$name] = $this->oDB->errno;
      $this->aError[$name] = $this->oDB->error;
      $this->aLastInsertId[$name] = $this->oDB->insert_id;
      $this->affectedRec[$name] = $this->oDB->affected_rows;
      return $this->oDB->errno;
   }
   
   function errno($name='default') {
      if (!isset($this->aErrno[$name])) return false;
      return $this->aErrno[$name];
   }
   function lastInsertId($name='default') {
      if (!isset($this->aLastInsertId[$name])) return false;
      return $this->aLastInsertId[$name];
   }
   function affectedRec($name='default') {
      if (!isset($this->affectedRec[$name])) return false;
      return $this->affectedRec[$name];
   }
   function error($name='default') {
      if (!isset($this->aError[$name])) return false;
      return $this->aError[$name];
   }
   function numRec($name='default') {
      if (!isset($this->aObjRes[$name])) return false;
      return $this->aObjRes[$name]->num_rows;
   }
   function free($name='default') {
      if (isset($this->aObjRes[$name])) {
         $this->aObjRes[$name]->free();
         unset($this->aObjRes[$name]);
         unset($this->aError[$name]);
         unset($this->aErrno[$name]);
         unset($this->aSql[$name]);
         unset($this->aLastInsertId[$name]);
         unset($this->affectedRec[$name]);
      }
      return true;
   }
   
   //restituisce un array ass. con le caratteristiche dei campi della query
   function fieldsDef($name='default') {
   	if (!isset($this->aObjRes[$name])) return false;
      $aFieldsDef = $this->aObjRes[$name]->fetch_fields();
      $this->aErrno[$name] = $this->oDB->errno;
      $this->aError[$name] = $this->oDB->errno;
      return $aFieldsDef;
   }
   
   //restituisce un array ass. del prossimo rec
   function fetch($name='default', $pos = '') {
   	if (!isset($this->aObjRes[$name]) || !is_object($this->aObjRes[$name])) return false;
      if ($pos != '' and $pos >= 0) {
      	$this->seekAt($pos, $name);
      }
      $rec = $this->aObjRes[$name]->fetch_assoc();
      $this->aErrno[$name] = $this->oDB->errno;
      $this->aError[$name] = $this->oDB->errno;
      return $rec;
   }
   
   //si riposiziona sul primo rec
   function seekFirst($name='default') {
      if (!isset($this->aObjRes[$name])) return false;
      if ($this->aObjRes[$name]->num_rows <= 0) return false;
      return $this->aObjRes[$name]->data_seek(0);
   }
   //si riposiziona sul rec con off-set $pos (1^ pos = 0)
   function seekAt($pos, $name='default') {
      if (!isset($this->aObjRes[$name])) return false;
      if ($this->aObjRes[$name]->num_rows() <= $pos) return false;
      return $this->aObjRes[$name]->data_seek($pos);
   }
   //restituisce un array ass. del primo rec (e si riposiziona li')
   function first($name='default') {
      if (!isset($this->aObjRes[$name])) return false;
      $this->seekFirst($name);
      $rec = $this->fetch[$name];
      $this->aErrno[$name] = $this->oDB->errno;
      $this->aError[$name] = $this->oDB->errno;
      return $rec;
   }
   
   function genSqlCampi($tab, $alias, $pref='') {
      if ($pref == '') { $pref = $alias."_"; }
      $sSql = "SHOW COLUMNS FROM $tab";
      $this->exec($sSql,'showColumns');
      $sNomi=$sep='';
      WHILE ($aRow = $this->fetch('showColumns')) {
        $sNomi .= $sep.$alias.".".$aRow['Field']." AS ".$pref.$aRow['Field'];
        $sep = ', ';
      }
      return $sNomi;
   }
   
   function insertFrom4db($tab, &$a4db, $pref, $opz='') {
      $ignore = '';
      $checkFields = false;
      if (is_array($opz)) {
         if (isset($opz['ignore']) and $opz['ignore'] == 'si') { $ignore = 'IGNORE'; }
         if (isset($opz['check_fields']) and $opz['check_fields'] == 'si') { $checkFields = true; }
      }
      $aFields = array();
      if ($checkFields) {
      	$this->exec("SHOW COLUMNS FROM $tab",'insertFromPost');
      	while($rec=$this->next('insertFromPost')) {
      		$aFields[] = $rec['Field'];
      	}
      }      
      $prefLen = strlen($pref);
      $sql = "INSERT $ignore INTO $tab SET ";
      foreach($a4db as $nome4db => $val4db) {
         if (substr($nome4db,0,$prefLen) != $pref) { continue; }
         if ($checkFields and !in_array(substr($nome4db,$prefLen), $aFields)) { continue; }
         $sql .= substr($nome4db,$prefLen)." = '".qnas($val4db)."', ";
      }
      $sql = substr($sql,0,-2);
      //dbg_($sql);
      $this->exec($sql,'insertFromPost');
      return $this->lastInsertId('insertFromPost');
   }
   
   function updateFrom4db($tab, &$a4db, $pref, $aKey, $opz='') {
      $prefLen = strlen($pref);
      $sqlSet = "UPDATE $tab SET ";
      $sqlWhere = " WHERE ";
      foreach($a4db as $nome4db => $val4db) {
         if (substr($nome4db,0,$prefLen) != $pref) { continue; }
         if (in_array($nome4db,$aKey) ) { 
            $sqlWhere .= substr($nome4db,$prefLen)." = '".qnas($val4db)."' AND ";
         } else {
            $sqlSet .= substr($nome4db,$prefLen)." = '".qnas($val4db)."', ";
         }
      }
      $sql = substr($sqlSet,0,-2).substr($sqlWhere,0,-4);
      return $this->exec($sql,'updateFromPost');
   }
   function readTo4db($tab, &$a4db, $pref, $aKey, $opz='') {
      $prefLen = strlen($pref);
      $sql = "SELECT * FROM $tab WHERE ";
      foreach($a4db as $nome4db => $val4db) {
         if (substr($nome4db,0,$prefLen) != $pref) { continue; }
         if (in_array($nome4db,$aKey) ) { 
            $sql .= substr($nome4db,$prefLen)." = '".qnas($val4db)."' AND ";
         } 
      }
      $sql = substr($sql,0,-4);
      $this->exec($sql,'readTo4db');
      if ($rec = $this->next('readTo4db')) {
         foreach($rec as $campo => $val) {
            $a4db[$pref.$campo] = $val;
         }
         return true;
      } 
      return false;
   }
}
